<template>
  <div class="ele-body">
    <el-card shadow="never" body-style="padding-top: 5px;">
      <el-tabs v-model="active" @tab-click="handleClick">
        <el-tab-pane
          v-for="(item, index) in configList"
          :key="index"
          :label="item.config_name"
          :name="`tab_${index}`"
          style="margin: 20px auto"
        >
          <el-form
            v-for="(subItem, subIdx) in item.item_list"
            :key="subIdx"
            :model="form"
            label-width="150px"
          >
            <!-- 单行文本框 -->
            <el-form-item
              v-if="subItem.type === 'text'"
              :label="`${subItem.title}:`"
              :prop="subItem.code"
            >
              <el-input
                v-model="form[subItem.code]"
                :placeholder="`请输入${subItem.title}`"
                clearable
              />
            </el-form-item>
            <!-- 多行文本框 -->
            <el-form-item
              v-if="subItem.type === 'textarea'"
              :label="`${subItem.title}:`"
              :prop="subItem.code"
            >
              <el-input
                v-model="form[subItem.code]"
                :placeholder="`请输入${subItem.title}`"
                :rows="3"
                type="textarea"
              />
            </el-form-item>
            <!-- 单图上传 -->
            <el-form-item
              v-if="subItem.type === 'image'"
              :label="`${subItem.title}:`"
            >
              <ImageUpload
                v-model="form[subItem.code]"
                :limit="1"
              />
            </el-form-item>
            <!-- 多图上传 -->
            <el-form-item
              v-if="subItem.type === 'images'"
              :label="`${subItem.title}:`"
            >
              <ImageUpload
                v-model="form[subItem.code]"
                :limit="10"
              />
            </el-form-item>
            <!-- 日期选择 -->
            <el-form-item
              v-if="subItem.type === 'date'"
              :label="`${subItem.title}:`"
              :prop="subItem.code"
            >
              <el-date-picker
                v-model="form[subItem.code]"
                type="date"
                :placeholder="`请选择${subItem.title}`"
                size="small"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              />
            </el-form-item>
            <!-- 日期时间选择 -->
            <el-form-item
              v-if="subItem.type === 'datetime'"
              :label="`${subItem.title}:`"
              :prop="subItem.code"
            >
              <el-date-picker
                v-model="form[subItem.code]"
                type="datetime"
                :placeholder="`请选择${subItem.title}`"
                size="small"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
            <!-- 单选按钮 -->
            <el-form-item
              v-if="subItem.type === 'radio'"
              :label="`${subItem.title}:`"
            >
              <el-radio-group v-model="form[subItem.code]">
                <el-radio
                  v-for="(val, key) in subItem.param"
                  :key="val"
                  :label="key"
                >
                  {{ val }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 数字输入框 -->
            <el-form-item
              v-if="subItem.type === 'number'"
              :label="`${subItem.title}:`"
              :prop="subItem.code"
            >
              <el-input-number
                v-model.number="form[subItem.code]"
                controls-position="right"
                :min="0"
                :placeholder="`请输入${subItem.title}`"
                class="ele-fluid ele-text-left"
              />
            </el-form-item>
            <!-- 密码输入框 -->
            <el-form-item
              v-if="subItem.type === 'password'"
              :label="`${subItem.title}:`"
              :prop="subItem.code"
            >
              <el-input
                v-model="form[subItem.code]"
                :placeholder="`请输入${subItem.title}`"
                show-password
              />
            </el-form-item>
            <!-- 复选框 -->
            <el-form-item
              v-if="subItem.type === 'checkbox'"
              :label="`${subItem.title}:`"
              :prop="subItem.code"
            >
              <el-checkbox-group v-model="form[subItem.code]">
                <el-checkbox
                  v-for="(val, key) in subItem.param"
                  :key="val"
                  :label="val"
                  :value="key"
                />
              </el-checkbox-group>
            </el-form-item>
            <!-- 下拉单选框 -->
            <el-form-item
              v-if="subItem.type === 'select'"
              :label="`${subItem.title}:`"
              :prop="subItem.code"
            >
              <el-select
                v-model="form[subItem.code]"
                :placeholder="`请选择${subItem.title}`"
                class="ele-block"
                clearable
              >
                <el-option
                  v-for="(val, key) in subItem.param"
                  :key="key"
                  :label="val"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <!-- 富文本编辑器 -->
            <el-form-item
              v-if="subItem.type === 'ueditor'"
              :label="`${subItem.title}:`"
            >
              <TinymceEditor :ref="el => editorRefs[subItem.code] = el" v-model="form[subItem.code]" :init="initEditor(subItem.code)" />
            </el-form-item>
          </el-form>
          <div style="margin-left: 100px">
            <el-button
              type="primary"
              :loading="loading"
              @click="save"
            >
              保存更改
            </el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import TinymceEditor from '@/components/TinymceEditor/index.vue'

defineOptions({
  name: 'ConfigWeb',
})

const configList = ref([])
const active = ref('tab_0')
const form = ref({})
const loading = ref(false)

const editorRefs = ref({})

onMounted(() => {
  // 获取配置信息
  utils.get('/config/index').then((res) => {
    if (res.code === 0) {
      if (res.data.length > 0) {
        configList.value = res.data
        const itemList = res.data[0].item_list
        form.value = formatForm(itemList)
      }
      else {
        form.value = {}
      }
    }
  })
})

function formatForm(list) {
  const res = {}
  list.forEach((item) => {
    res[item.code] = item.type === 'number' ? Number(item.value) : item.value
  })
  return res
}

/* 保存更改 */
function save() {
  loading.value = true
  utils
    .post('/configweb/edit', form.value)
    .then((res) => {
      loading.value = false
      utils.message(res.msg, res.code)
    })
}
/**
 * Tab点击事件
 * @param tab
 */
function handleClick(tab) {
  const itemList = configList.value[tab.index].item_list
  form.value = formatForm(itemList)
}

/** 编辑器配置 */
function initEditor(code) {
  return ({
    height: 520,
    // 自定义文件上传(这里使用把选择的文件转成blob演示)
    file_picker_callback: (callback, _value, meta) => {
      const input = document.createElement('input')
      input.setAttribute('type', 'file')
      // 设定文件可选类型
      if (meta.filetype === 'image')
        input.setAttribute('accept', 'image/*')
      else if (meta.filetype === 'media')
        input.setAttribute('accept', 'video/*')

      input.onchange = () => {
        const file = input.files?.[0]
        if (!file)
          return

        if (meta.filetype === 'media') {
          if (!file.type.startsWith('video/')) {
            editorRefs.value[code]?.alert?.({ content: '只能选择视频文件' })
            return
          }
        }
        if (file.size / 1024 / 1024 > 20) {
          editorRefs.value[code]?.alert?.({ content: '大小不能超过 20MB' })
          return
        }
        // 实际项目这里应该上传到后端得到文件url而不是转成blob
        const reader = new FileReader()
        reader.onload = (e) => {
          if (e.target?.result != null) {
            const blob = new Blob([e.target.result], { type: file.type })
            callback(URL.createObjectURL(blob), {
              text: file.name,
              alt: file.name,
            })
          }
        }
        reader.readAsArrayBuffer(file)
      }
      input.click()
    },
  })
}
</script>
